import { SchemaManage } from '@/components/SchemaComponent';
import { useEffect, useMemo, useRef, useState } from 'react';
import { connect } from 'umi';
import { ManageCommonAPI } from '@/pages/type';
import { ContractManageAPI } from '../common/manageType';
import { Table, Typography } from 'antd';
import '../common/manageStyle.less';
import { contractManageService } from '../services';
import { getTableColumns, float_add } from '../mconfig';
import { history } from 'umi';
import { getKeyRouter } from '@/utils';
import moment from 'moment';

const ContractManageView: React.FC<ContractManageAPI.IManageType> = ({ curRes, locationProps }) => {
  const schemaManageRef: any = useRef();
  const { Text } = Typography;
  const manageFixStyle: string = 'contract-manage-count-style-';

  /**  获取管理页数据 */
  const { data, loading, searchList, getContractData, allSearchParams } = contractManageService(curRes, {});

  const [dataSource, setDataSource] = useState(data?.obj);

  /**将筛选条件放入列表数据 */
  useEffect(() => {
    let arr: Record<string, any> = [];
    data?.obj.forEach((element) => {
      arr.push({
        ...element,
        allSearchParams: allSearchParams,
        random: `${element?.departmentID}${getKeyRouter()}`,
      });
    });
    setDataSource(arr);
  }, [data]);

  /**
   * 设置筛选条件中默认数据
   * */
  useEffect(() => {
    schemaManageRef?.current?.setSearch({
      capitalDir: '0',
      currencyType: '100123121000',
      realTime: [moment().startOf('year'), moment()],
    });
  }, [locationProps?.state]);

  /**  重置搜索表单方法 */
  const onReset = (values: any) => {
    getContractData({ ...values });
  };

  /**  搜索列表 */
  const onSearch = (request: ManageCommonAPI.IGridRequestType) => {
    getContractData({ ...request });
  };

  /** 表格操作按钮点击方法 */
  const onOptClick = {
    onView: async (resObj) => {
      let searchInitParam = resObj?.allSearchParams;
      history.push({
        pathname: `/contractController/performManage`,
        state: {
          searchInitParam: {
            createDepartmentID: resObj?.departmentID,
            realBeginTime: searchInitParam?.startTime,
            realFinishTime: searchInitParam?.endTime,
            currencyType: searchInitParam?.currencyType,
            businessType: searchInitParam?.businessType,
            capitalDir: searchInitParam?.capitalDir,
          },
          random: resObj?.random,
        },
      });
    },
  };

  /** 获取columns方法 */
  const columns: Record<string, any>[] = useMemo(() => {
    return getTableColumns(curRes, onOptClick, manageFixStyle);
  }, [curRes, manageFixStyle]);

  return (
    <div
      style={{
        width: '100%',
        height: '100%',
        overflow: 'hidden',
        position: 'relative',
      }}
    >
      <div className={`${manageFixStyle}`}>
        <SchemaManage
          ref={schemaManageRef}
          searchProps={{
            switchList: [],
            searchList,
            onSwitch: () => {},
            onReset,
            onSearch,
          }}
          actionList={[]}
          tableProps={{
            columns,
            dataSource: dataSource || [],
            loading: loading,
            rowKey: 'departmentID',
            summary: (pageData) => {
              if (pageData?.length) {
                let total_Sum = '0';
                let total_Residue = '0';
                let total_Paid = '0';
                let total_Num = 0;
                pageData.forEach(({ totalSum, totalResidue, totalPaid, totalNum }) => {
                  total_Sum = float_add(total_Sum, totalSum, 2);
                  total_Residue = float_add(total_Residue, totalResidue, 2);
                  total_Paid = float_add(total_Paid, totalPaid, 2);
                  total_Num += totalNum;
                });
                return (
                  <>
                    <Table.Summary.Row>
                      <Table.Summary.Cell index={0}>
                        <Text>合计</Text>
                      </Table.Summary.Cell>
                      <Table.Summary.Cell index={1}>
                        <Text>{total_Num}</Text>
                      </Table.Summary.Cell>
                      <Table.Summary.Cell index={2}>
                        <Text>{total_Sum}</Text>
                      </Table.Summary.Cell>
                      <Table.Summary.Cell index={3}>
                        <Text>{total_Paid}</Text>
                      </Table.Summary.Cell>
                      <Table.Summary.Cell index={4}>
                        <Text>{total_Residue}</Text>
                      </Table.Summary.Cell>
                    </Table.Summary.Row>
                  </>
                );
              } else {
                return <></>;
              }
            },
          }}
        />
      </div>
    </div>
  );
};

export default connect(({ baseLogin }: Record<string, any>) => ({
  curRes: baseLogin?.permissions,
}))(ContractManageView);
